package com.wstuo.common.md5;

import java.security.MessageDigest;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

/**
 *  JAVA自带md5加密
 * @author mark
 *
 */
public class Md5Util {
	final static Logger LOGGER = Logger.getLogger(Md5Util.class);
	/**
	 *  MD5加密
	 * @param s 要加密的字符串
	 * @return  加密后字符串
	 */
	 public   final   static  String MD5Encrypt(String s) {
		 String result = null;
		  char  hexDigits[] = {  '0' ,  '1' ,  '2' ,  '3' ,  '4' ,  '5' ,  '6' ,  '7' ,  '8' ,  '9' ,  
		    'A' ,  'B' ,  'C' ,  'D' ,  'E' ,  'F'  };  
		  try  {  
			   byte [] strTemp = s.getBytes();  
			   MessageDigest mdTemp = MessageDigest.getInstance("MD5" );  
			   mdTemp.update(strTemp);  
			   byte [] md = mdTemp.digest();  
			   int  j = md.length;  
			   char  str[] =  new   char [j *  2 ];  
			   int  k =  0 ;  
			   for  ( int  i =  0 ; i < j; i++) {  
				    byte  byte0 = md[i];  
				    str[k++] = hexDigits[byte0 >>> 4  &  0xf ];  
				    str[k++] = hexDigits[byte0 & 0xf ];  
			   }  
			   result = new  String(str);  
		  } catch  (Exception e) {  
			  LOGGER.error(e);
		  }  
		  return result;
	 } 
	 
	 /**
	  *  可逆加密
	  * @param inStr 需要可逆加密的字符串
	  * @return 可逆加密后的字符串
	  */
	 public  static  String ReversibleEncrypt(String inStr) {  
		  char [] a = inStr.toCharArray();  
		  for  ( int  i =  0 ; i < a.length; i++) {  
			  a[i] = (char ) (a[i] ^  't' );  
		  }  
		  String s = new  String(a);  
		  return  s;  
	 }  
	  
	 /**
	  *  解密
	  * @param inStr 要解密的字符串 
	  * @return 解密后的字符串
	  */
	 public   static  String Decryption(String inStr) {
		 String result = "";
		 if(StringUtils.hasText(inStr)){
		  char [] a = inStr.toCharArray();  
		  for  ( int  i =  0 ; i < a.length; i++) {  
		   a[i] = (char ) (a[i] ^  't' );  
		  }  
		  result = new  String(a);  
		 }
		 return result;
	 }  
}
